package com.leetcode.p0;

public class Test27_2 {

    /**
     * 双指针法的优化
     * 2, 3, 4, 1   ->  1, 3, 4, 2
     * 1, 3, 4
     * 3, 4
     * 3
     * 相比上种方法，在相同的数据中，交换只发生了一次
     */
    public int removeElement(int[] nums, int val) {
        int left = 0, right = nums.length - 1;

        while (left <= right) {
            if (nums[left] == val) {
                nums[left] = nums[right];
                right--;
            } else {
                left++;
            }
        }

        return left;
    }

    public static void swap(int[] arr, int i, int j) {
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {
//        int[] data = new int[]{2, 3, 4, 1, 2, 2, 8,2};
//        int[] data = new int[]{2, 2, 2, 4};
        int[] data = new int[]{3, 2, 2, 3};

        Test27_2 test = new Test27_2();
        int count = test.removeElement(data, 3);

        for (int i = 0; i < count; i++) {
            System.out.println(data[i]);
        }
    }

}
